package com.yazi.mxz.gather.main.store;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;



import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.yazi.mxz.gather.common.App;
import com.yazi.mxz.gather.entity.enums.ProcessType;
import com.yazi.mxz.gather.entity.http.ChachabaResBody4List;
import com.yazi.mxz.gather.entity.http.ChachabaResBody4List.Ul;
import com.yazi.mxz.gather.entity.repository.ProcessLog;
import com.yazi.mxz.gather.entity.repository.Store;
import com.yazi.mxz.gather.repository.ProcessLogRepository;
import com.yazi.mxz.gather.repository.StoreRepository;

/**
 * 查查吧
 * http://www.chachaba.com
 * @author mo_yq5
 * @date 2015-8-17
 */
public class ChachabaCom extends Thread {
	
	private CloseableHttpAsyncClient httpclient;
	private ProcessLogRepository logRepository;
	private StoreRepository storeRepository;
	private ObjectMapper om;
	
	
	public ChachabaCom() {
		init();
	}
	
	public ChachabaCom(int startPage, int endPage) {
		init();
		ProcessLog log = logRepository.findOne(ProcessType.CHACHABA.ordinal());
		if (null == log) {
			log = new ProcessLog();
			log.setId(ProcessType.CHACHABA.ordinal());
			log.setCur((long)startPage);
			log.setEnd((long)endPage);
			log.setCount(0);
			logRepository.insert(log);
		} else {
			log.setCur((long)startPage);
			log.setEnd((long)endPage);
			logRepository.save(log);
		}
	}
	
	public void init() {
		
		storeRepository = App.context.getBean(StoreRepository.class);
		logRepository = App.context.getBean(ProcessLogRepository.class);
		
		httpclient = HttpAsyncClients.createDefault();
		httpclient.start();
		
		om = new XmlMapper();
		om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		System.out.println(storeRepository.count());
	}

	@Override
	public void run() {
		
		ProcessLog log = logRepository.findOne(ProcessType.CHACHABA.ordinal());
		if (null == log) {
			System.out.println(ProcessType.CHACHABA + "日志不存在");
			return;
		}
		boolean isContinue = false;
		
		try {
			
			
			while (true) {
				
				if (log.getCur() > log.getEnd()) {
					isContinue = false;
					break;
				}
				
				barcodeInfo(log.getCur());
				
				log.setCur(log.getCur() + 1);
				logRepository.save(log);
			
				sleep(200);
			}
			
		} catch (SocketException e) {
			e.printStackTrace();
			isContinue = true;
			
		} catch (Exception e1) {
			e1.printStackTrace();
			
		} 
		if (isContinue) {
			run();
		} else {
			System.out.println("执行结束！");
		}
	}
	
	private void barcodeInfo(long pageNum) throws JsonParseException, JsonMappingException,
			IOException, InterruptedException, ExecutionException {
		
		System.out.println("PageNum:" + pageNum);
		
		final HttpGet req = new HttpGet("http://www.chachaba.com/cccb/search!localSearch.action?pageSize=15&name=%E7%99%BE%E8%B4%A7%E8%B6%85%E5%B8%82&cityPy=nanning&citymc=%E5%8D%97%E5%AE%81&n=22.825&e=108.315&_page=" + pageNum);
		Future<HttpResponse> future = httpclient.execute(req, null);
		HttpResponse res = future.get();
		
		System.out.println(req.getRequestLine() + "->" + res.getStatusLine());
		
		StringBuffer bodySb = new StringBuffer(EntityUtils.toString(res.getEntity(), "utf-8"));
		if (bodySb.length() == 0) {
			System.out.println("无响应内容!");
			return;
		}
		
		StringBuffer listSb = new StringBuffer();
		String str = "<div class='company_l'>";
		int start = 0;
		int end =  0;	
		listSb.append(bodySb.substring(start, end));
		while(true) {
			start = bodySb.indexOf(str, start);
			if (start == -1) {
				break;
			}
			start += str.length();
			end = bodySb.indexOf("</div>", start);
			listSb.append(bodySb.substring(start, end));
			start = end;
		}
		
		String listStr = ("<data>" + listSb.toString() + "</data>")
				.replaceAll("<li class='name'>", "<li>")
				.replaceAll("<li>", "<li><![CDATA[")
				.replaceAll("</li>", "]]></li>");

		System.out.println(listStr);
		ChachabaResBody4List ccb4List = om.readValue(listStr, ChachabaResBody4List.class);
		List<Ul> uls = ccb4List.getUls();
		StringBuffer goodsInfo = new StringBuffer();
		String name, tel, addr;
		Store store;
		for (Ul ul : uls) {
			name = om.readValue(ul.getLis().get(0).getText(), ChachabaResBody4List.A.class).getStrong().getText();// 名称
			tel = ul.getLis().get(1).getText().replace("电话：", "").replaceAll("&nbsp;", "").trim(); // 电话
			addr = ul.getLis().get(2).getText().replace("地址：", "").trim(); // 地址
			if (!addr.isEmpty()) {
				
				goodsInfo = new StringBuffer();
				goodsInfo.append("\r\n名称:" + name);
				goodsInfo.append("\r\n电话:" + tel);
				goodsInfo.append("\r\n地址:" + addr);
				System.out.println(goodsInfo);
				
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				if(br.readLine().isEmpty()) {
					store = new Store();
					store.setAddr(addr);
					store.setIsUpload(false);
					store.setName(name);
					store.setTel(tel);
					storeRepository.insert(store);
					System.out.println("ok!");
					
				}
				
			}
		}
		
	}
	
}
